package cn.cvs.controller;

import cn.cvs.entity.Fruit;
import cn.cvs.service.FruitService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class FruitController {

    @Autowired
    private FruitService fruitService;

    @GetMapping("/list")
    public String list(Model model){

        List<Fruit> list = fruitService.list();

        model.addAttribute("list",list);

        return "list";
    }

    @GetMapping("/fruit/{id}")
    public String view(Model model,@PathVariable(value = "id") Integer id){
        Fruit fruit = fruitService.selectById(id);
        model.addAttribute("fruit",fruit);
        return "view";
    }

    @ResponseBody
    @GetMapping("/view/{id}")
    public Fruit viewJson(@PathVariable(value = "id") Integer id){
        Fruit fruit = fruitService.selectById(id);

        // String jsonString = JSON.toJSONString(fruit);

        return fruit;
    }

    //  @ResponseBody 将返回的内容放入 响应体中
    @ResponseBody
    @DeleteMapping("/fruit/{id}")
    public String delete(@PathVariable Integer id){

        int result = fruitService.delete(id);
        if (result>0){
            // 删除成功  响应 success 字符串出去

            return "success";
        }

        return "error";
    }

    // @ResponseBody
    // @PostMapping(value = "/add",produces = {"text/html;charset=UTF-8"})
    @PostMapping(value = "/add")
    public String add(HttpServletRequest request, Model model, @Valid Fruit fruit, BindingResult bindingResult, MultipartFile filePic) throws IOException {
        if (bindingResult.hasFieldErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }
            return "add";
        }

        // d:/323/upload/aaa.jpg
        // 目录 d:/323/upload/
        // D:\323\demo\fruit\out\artifacts\fruit_war_exploded\statics\
        String directory = request.getSession().getServletContext().getRealPath("statics");
        // 文件名： aaa.jpg
        String fileName = RandomUtils.nextInt(1000000)+"_pic";
        // 文件后缀
        String suffix = FilenameUtils.getExtension(filePic.getOriginalFilename());

        fileName = fileName+"."+suffix;
        //完整的文件路径
        String path = directory+File.separator+fileName;

        File targetFile = new File(path);

        if (!targetFile.exists()){
            targetFile.mkdirs();
        }

        // 核心， 将filePic 传输 到一个指定的 文件
        filePic.transferTo(targetFile);

        fruit.setPic(fileName);

        int result = fruitService.add(fruit);
        if (result>0){
            //新增成功
            return "redirect:list";
        }
        model.addAttribute("fruit",fruit);
        return "add";
    }

    @ResponseBody
    @GetMapping("/checkType")
    public String checkType(String type){

        Fruit fruit = fruitService.selectByType(type);
        if (fruit == null){
            return "false";
        }

        return "true";
    }
}
